package com.spzx.order.listener;

import com.spzx.common.rabbitmq.constants.SpzxRabbitmqConstants;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class SpzxOrderMqConfig {
    //死信队列交换机 绑定： 延迟接收业务队列的消息  ， 延迟关单的消费者 消费死信队列中的消息
    @Bean
    public Exchange orderDelayExchange(){
        return ExchangeBuilder.topicExchange(SpzxRabbitmqConstants.ORDER_DELAY_EXCHANGE)
                .durable(true)
                .build();
    }
    @Bean
    public Queue orderDelayQueue(){
        return QueueBuilder.durable(SpzxRabbitmqConstants.ORDER_DELAY_QUEUE)
                .build();
    }
    @Bean
    public Binding orderDelayBinding(Exchange orderDelayExchange , Queue orderDelayQueue ){
        return BindingBuilder
                .bind(orderDelayQueue)
                .to(orderDelayExchange)
                .with(SpzxRabbitmqConstants.ORDER_DELAY_ROUTING_KEY)
                .noargs();
    }
    //业务队列交换机 绑定： 设置过期时间 并绑定死信队列
    //提交订单交换机
    @Bean
    public Exchange orderCloseExchange(){
        return ExchangeBuilder.topicExchange(SpzxRabbitmqConstants.ORDER_SUBMIT_EXCHANGE)
                .durable(true)
                .build();
    }
    // 提交订单的消息--> order.submit.exchange->  order.cart.queue/ order.close.queue
    // order.close.queue--> order.delay.exchage -> order.delay.queue
    //关单业务队列： 绑定延迟队列  消息30秒后 如果未被消费变为死信 自动进入延迟队列
    @Bean
    public Queue orderCloseQueue(){
        return QueueBuilder.durable(SpzxRabbitmqConstants.ORDER_CLOSE_QUEUE)
                .ttl(30*60*1000)
                .deadLetterExchange(SpzxRabbitmqConstants.ORDER_DELAY_EXCHANGE)
                .deadLetterRoutingKey(SpzxRabbitmqConstants.ORDER_DELAY_ROUTING_KEY)
                .build();
    }
    @Bean
    public Binding orderCloseBinding(Exchange orderCloseExchange , Queue orderCloseQueue ){
        return BindingBuilder
                .bind(orderCloseQueue)
                .to(orderCloseExchange)
                .with(SpzxRabbitmqConstants.ORDER_SUBMIT_ROUTING_KEY)
                .noargs();
    }

}
